﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Identify
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string identity = textBox1.Text;
            string pattern = "^[0-9]{6}(18|19|20)[0-9]{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])[0-9]{3}[0-9A-Za-z]$";
  
            bool ok = Regex.IsMatch(identity,pattern);
  
            //将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为：7－9－10－5－8－4－2－1－6－3－7－9－10－5－8－4－2。
            int sum = (identity[0] - '0') * 7 + (identity[1] - '0') * 9 + (identity[2] - '0') * 10 + (identity[3] - '0') * 5 + (identity[4] - '0') * 8 + (identity[5] - '0') * 4 + (identity[6] - '0') * 2 + (identity[7] - '0') * 1 + (identity[8] - '0') * 6 + (identity[9] - '0') * 3 +
                (identity[10] - '0') * 7 + (identity[11] - '0') * 9 + (identity[12] - '0') * 10 + (identity[13] - '0') * 5 + (identity[14] - '0') * 8 + (identity[15] - '0') * 4 +
                (identity[16] - '0') * 2;
            sum %= 11;
            bool last = false;
            //余数只可能有0－1－2－3－4－5－6－7－8－9－10这11个数字。其分别对应的最后一位身份证的号码为1－0－X－9－8－7－6－5－4－3－2。
            switch (sum) 
            {
                case 0: if (identity[17] == '1') last = true; break;
                case 1: if (identity[17] == '0') last = true; break;
                case 2: if (identity[17] == 'X') last = true; break;
                case 3: if (identity[17] == '9') last = true; break;
                case 4: if (identity[17] == '8') last = true; break;
                case 5: if (identity[17] == '7') last = true; break;
                case 6: if (identity[17] == '6') last = true; break;
                case 7: if (identity[17] == '5') last = true; break;
                case 8: if (identity[17] == '4') last = true; break;
                case 9: if (identity[17] == '3') last = true; break;
                case 10: if (identity[17] == '2') last = true; break;
                default:break;
            }

            if (ok&&last)
            {
                MessageBox.Show("匹配成功！");
            }
            else
            {
                MessageBox.Show("匹配失败，输入身份证号有误！");
            }
        }
    }
}
